package com.app.mymusic.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.app.mymusic.model.PieDatas;
import com.app.mymusic.utils.LogUtil;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/11/16.
 */

public class PieView extends View {
    private Paint mPaint;
    // 颜色表 (注意: 此处定义颜色使用的是ARGB，带Alpha通道的)
    private int[] mColors = {0xFFCCFF00, 0xFF6495ED, 0xFFE32636, 0xFF800000, 0xFF808000, 0xFFFF8C69, 0xFF808080,
            0xFFE6B800, 0xFF7CFC00};
    // 饼状图初始绘制角度
    private float mStartAngle = 0;
    // 数据
    private ArrayList<PieDatas> mData=new ArrayList<>();
    // 宽高
    private int mWidth, mHeight;

    public PieView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint=new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
        initDatas();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float currentStartAngle = mStartAngle;                    // 当前起始角度
        canvas.translate(mWidth / 2, mHeight / 2);                // 将画布坐标原点移动到中心位置
        float r = (float) (Math.min(mWidth, mHeight) / 2 * 0.8);  // 饼状图半径
        RectF rect = new RectF(-r, -r, r, r);                     // 饼状图绘制区域
        LogUtil.showLog("r:"+r+"mdatas:"+mData.size());
        for (int i = 0; i < mData.size(); i++) {
            PieDatas pie = mData.get(i);
            mPaint.setColor(mColors[i]);
            LogUtil.showLog("currentStartAngle:"+currentStartAngle+"-"+"end:"+pie.getAngle());
            canvas.drawArc(rect, currentStartAngle, pie.getAngle(), true, mPaint);
            currentStartAngle += pie.getAngle();
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
    }

    public void initDatas(){

        float sumValue = 0;

        for(int i=0;i<9;i++){
            PieDatas p=new PieDatas();
            p.setValue(i*3);
            mData.add(p);
            sumValue+=mData.get(i).getValue();
        }

        float sumAngle = 0;
        for(int i=0;i<mData.size();i++){
            PieDatas pie=mData.get(i);
            float percentage=pie.getValue()/sumValue;
            float angle = percentage * 360;
            pie.setPercentage(percentage);
            pie.setAngle(angle);
        }
    }
}
